package com.tian.scroll.pull

import android.graphics.Color
import android.os.Bundle
import android.util.Log
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.tian.scroll.databinding.FragmentPullRefreshNestedBinding

/**
 * @author tiansongtao, Email:tiansongtao@up366.com
 * @date 2022/12/8 11:44
 */
class PullRefreshFragment : Fragment() {


    private lateinit var b: FragmentPullRefreshNestedBinding

    private val data: MutableList<String> by lazy {
        val t = mutableListOf<String>()
        for (i in 0..20) {
            t.add("tiansong $i")
        }
        t
    }


    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        b = FragmentPullRefreshNestedBinding.inflate(inflater)
        return b.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        b.recyclerView.layoutManager = LinearLayoutManager(requireContext())
        b.recyclerView.adapter = MyAdapter()
        b.refreshLayout.setOnPullDownListener {
            b.refreshLayout.postDelayed({ b.refreshLayout.complete() }, 1000)
        }
        b.refreshLayout.setContentView(b.nsLl)
        b.rvHeader.setOnClickListener {
            b.tvHeader.visibility = View.GONE
        }
    }


    inner class MyAdapter : RecyclerView.Adapter<RecyclerView.ViewHolder>() {
        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
            val textView = TextView(parent.context)
            val lp = RecyclerView.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, 150).also {
                it.setMargins(30, 10, 30, 10)
            }
            textView.layoutParams = lp
            textView.gravity = Gravity.CENTER
            textView.setBackgroundColor(Color.BLUE)
            textView.textSize = 20f
            textView.setTextColor(Color.WHITE)
            return MyViewHolder(textView)
        }


        override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
            Log.i("tiansongtao", "pull recyclerview bind position=$position")
            (holder.itemView as TextView).text = "${data[position]} --- $position"
        }

        override fun getItemCount() = data.size

    }

    inner class MyViewHolder(view: View) : RecyclerView.ViewHolder(view)

}